//
//  EventListViewController.m
//  RONGAO
//
//  Created by wei wang on 2017/3/16.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "EventListViewController.h"
#import "EventHeadView.h"
#import "DateSelctViewController.h"
#import "Event.h"
//#import "PlayBackViewController.h"

#import "CameraPlaybackController.h"
#import "DeviceHeadView.h"
#import "NSDate+FIDString.h"
#import "NSString+FIDDate.h"
#ifndef SORTE_LIST
#define SORTE_LIST
#endif

#ifndef DOWNLOAD_REMOTE_RECORD
#define DOWNLOAD_REMOTE_RECORD
#endif


#define MAX_RECORD_SIZE_MB      150

#define ALERT_TAG_DEL_RECORD    2
#define ALERT_TAG_RECORD_FAIL   13



#define TAG_CELL_0          0
#define TAG_CELL_VIEW1      1
#define TAG_CELL_LINE       2
#define TAG_CELL_IMG_DEL    3
#define TAG_CELL_BNT_DEL    4
#define TAG_CELL_LAB_TYPE   5
#define TAG_CELL_LAB_TIME   6
#define TAG_CELL_IMG_DLD    7
#define TAG_CELL_BNT_DLD    8


#define START_STRING		"Start"
#define RDT_WAIT_TIMEMS		30000
//#define MAX_BUF_SIZE		102400
#define MAX_BUF_SIZE		1024


#define MAX_MEM_USE			1024000

// RDT Struct command-type
typedef enum
{
    RDT_FILE_TOTAL          = 0x00,         // file total
    RDT_FILE_NAME           = 0x01,         // file name
    RDT_FILE_SIZE           = 0x02,         // file size
    RDT_FILE_TIMES          = 0x03,         // same file, times
    RDT_FILE_START          = 0x04,         // file start
    RDT_FILE_STOP           = 0x05,         // file stop
    RDT_START               = 0x06,         // RDT start
    RDT_STOP                = 0x07,         // RDT stop
    RDT_NEXT_FILE           = 0x08,         // next file
} ENUM_RDT_COMMAND;

// RDT Struct
typedef struct
{
    char type;              // ENUM_RDT_COMMAND
    char content[127];       // command -> content
} RDTCommandStruct;



@interface EventListViewController ()<UITableViewDelegate,UITableViewDataSource,MyCameraDelegate>
{
    
    NSMutableArray *event_list;
    STimeDay start, stop;
    STimeDay searchStart;
    STimeDay searchStop;
    
}
/** tableView **/
@property(nonatomic,strong) UITableView *tableView;


@property (nonatomic, retain) MyCamera *camera;

@property (nonatomic, retain) NSString *selectFileName;
@property (nonatomic, retain) NSString *selectFilePath;


/** starTime **/
@property(nonatomic,strong) NSString *starTime;

/** endTime **/
@property(nonatomic,strong) NSString *endTime;

/** totalTime **/
@property(nonatomic,strong) NSString *totalTime;

@property (nonatomic, retain) Event *selectEvent;

@end

static NSString * HeadView = @"EventHeadView";

@implementation EventListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    event_list = [[NSMutableArray alloc] init];
    self.camera = [AppDelegate globalDelegate].cameraModel;
    [self setNavigationStyle];
    [self masLayoutSubview];
    [self loadData:2];
    self.selectFileName = @"";
    self.selectFilePath = @"";
    [self.tableView registerNib:[UINib nibWithNibName:HeadView bundle:nil] forHeaderFooterViewReuseIdentifier:HeadView];
}
- (void)setNavigationStyle{
    
    [self setNavigationTitle:@"设备视频" titleColor:[UIColor colorWithRed:210/255.0 green:177/255.0 blue:104/255.0 alpha:1]];
    [self setLeftButtonImage:[UIImage imageNamed:@"icon_back_nor"]];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_search_nor"]];
    
}

- (void)onRightButtonClick:(id)sender{
    
    DateSelctViewController *vc = [DateSelctViewController new];
    __weak typeof(self) weakself = self;
    vc.TimeEvent = ^(NSInteger type){
       
        [weakself loadData:type];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    if (self.camera != nil)
        self.camera.delegate2 = self;

}
- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    self.camera.delegate2 = nil;
    [SVProgressHUD dismiss];

}

#pragma mark - --------------------------默认获取视频的时间= 当前时间 - 12小时--------------------------
- (void)loadData:(NSInteger)type{

    NSDate *now = [NSDate date];
    NSDate *from = [NSDate date];
    NSDate *Timefrom;
    

    switch (type) {
        case 0:
        {
            from = [NSDate dateWithTimeIntervalSinceNow:- (60 * 60)];
            Timefrom = [NSDate dateWithTimeIntervalSince1970:[now timeIntervalSince1970] - (60 * 60)];

        }
            break;
            case 1:
        {
            Timefrom = [NSDate dateWithTimeIntervalSince1970:[now timeIntervalSince1970]-(60 * 60 * 6)];

            from = [NSDate dateWithTimeIntervalSinceNow:- (60 * 60 * 6)];

        }
            break;
            case 2:
        {
            from = [NSDate dateWithTimeIntervalSinceNow:- (60 * 60 * 12)];
            Timefrom = [NSDate dateWithTimeIntervalSince1970:[now timeIntervalSince1970]-(60 * 60 * 12)];

        }
            break;
            
            case 3:
        {
            from = [NSDate dateWithTimeIntervalSinceNow:- (60 * 60 * 24 * 7)];
            Timefrom = [NSDate dateWithTimeIntervalSince1970:[now timeIntervalSince1970]-(60 * 60 * 24 * 7)];

        }
            break;
           
        default:
            break;
    }

    
    
    start = [Event getTimeDay:[from timeIntervalSince1970]];
    stop = [Event getTimeDay:[now timeIntervalSince1970]];
    
    
    [self searchEventFrom:start To:stop];
}

#pragma mark - UICustomPeriodEventSearchControllerDelegate
-(void)customPeriodChanged:(NSDate*)from dateTo:(NSDate*)to; {
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mma"];
    
    NSLog( @"todo search %@ ~ %@", [dateFormatter stringFromDate:from], [dateFormatter stringFromDate:to] );
    
    
    STimeDay Start, Stop;
    
    Start = [Event getTimeDay:[from timeIntervalSince1970]];
    Stop = [Event getTimeDay:[to timeIntervalSince1970]];
    
    searchStart = Start;
    searchStop = Stop;
    
    [self searchEventFrom:Start To:Stop];
}



//将UTC日期字符串转为本地时间字符串
//输入的UTC日期格式2013-08-03T04:53:51+0000
-(NSString *)getLocalDateFormateUTCDate:(NSString *)utcDate
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //输入格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
    NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:localTimeZone];
    
    NSDate *dateFormatted = [dateFormatter dateFromString:utcDate];
    //输出格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:dateFormatted];

    return dateString;
}

- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}
- (void)searchEventFrom:(STimeDay)Tstart To:(STimeDay)Tstop {
    
    
    [event_list removeAllObjects];
    [self.tableView reloadData];

    

    
    
    self.starTime = [NSString stringWithFormat:@"%.4d-%.2d-%.2d %.2d:%.2d:%.2d", Tstart.year, Tstart.month, Tstart.day, Tstart.hour, Tstart.minute, Tstart.second];
    self.endTime = [NSString stringWithFormat:@"%.4d-%.2d-%.2d %.2d:%.2d:%.2d", Tstop.year, Tstop.month, Tstop.day, Tstop.hour, Tstop.minute,Tstop.second];
    
    NSDate *superdate = [NSDate getDateWithString:self.starTime stringDateFormatter:@"yyyy-MM-dd HH:mm:ss"];
    NSString *superStarTime = [NSString getYearDateWithDaySince1970:superdate.timeIntervalSince1970 dateFormat:@"yyyy-MM-dd HH:mm - "];
  
    NSDate *superenddate = [NSDate getDateWithString:self.endTime stringDateFormatter:@"yyyy-MM-dd HH:mm:ss"];
    NSString *superEndTime = [NSString getYearDateWithDaySince1970:superenddate.timeIntervalSince1970 dateFormat:@" MM-dd HH:mm"];
    
    self.totalTime = [superStarTime stringByAppendingString:superEndTime];
    NSLog(@"Time:%@",self.totalTime);

    NSLog(@"start  %d-%d-%d %d:%d:%d", Tstart.year, Tstart.month, Tstart.day, Tstart.hour, Tstart.minute, Tstart.second);
    NSLog(@"stop   %d-%d-%d %d:%d:%d", Tstop.year, Tstop.month, Tstop.day, Tstop.hour, Tstop.minute, Tstop.second);
    
    SMsgAVIoctrlListEventReq *req = (SMsgAVIoctrlListEventReq *) malloc(sizeof(SMsgAVIoctrlListEventReq));
    memset(req, 0, sizeof(SMsgAVIoctrlListEventReq));
    
    req->channel = 0;
    req->event = 0;
    req->stStartTime = Tstart;
    req->stEndTime = Tstop;
    
    [self.camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_LISTEVENT_REQ Data:(char *)req DataSize:sizeof(SMsgAVIoctrlListEventReq)];
    
    free(req);
    
    [SVProgressHUD showWithStatus:@"loading..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(180 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
    
}

- (double)getTimeInMillis:(STimeDay)time {
    
    double result;
    
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    
    [comps setYear:time.year];
    [comps setMonth:time.month];
    [comps setWeekday:time.wday];
    [comps setDay:time.day];
    [comps setHour:time.hour];
    [comps setMinute:time.minute];
    [comps setSecond:time.second];
    
    
    NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    [cal setLocale:[NSLocale currentLocale]];
    
    NSDate *date = [cal dateFromComponents:comps];
    
    result = [date timeIntervalSince1970];
    
    return result;
}


- (NSString *) pathForDocumentsResource:(NSString *) relativePath {
    
    static NSString* documentsPath = nil;
    
    if (nil == documentsPath) {
        
        NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsPath = [dirs objectAtIndex:0];
    }
    
    return [documentsPath stringByAppendingPathComponent:relativePath];
}


#pragma mark - tableView Datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [event_list count];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 54;
    
}

#pragma mark - tableView Delegate
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil) {
    
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#56504f"];
        [cell.textLabel setFont:[UIFont systemFontOfSize:15.f]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.detailTextLabel setFont:[UIFont systemFontOfSize:14.f]];
        cell.detailTextLabel.textColor = [UIColor colorWithHexString:@"#84807f"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    Event *info = event_list[indexPath.row];
    cell.textLabel.text = [Event getEventTypeName:info.eventType];
    
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:info.eventTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    
    cell.detailTextLabel.text = [dateFormatter stringFromDate:date];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    Event *evt = [event_list objectAtIndex:[indexPath row]];

    if (![self.camera getPlaybackSupportOfChannel:0] || evt.eventStatus == EVENT_NORECORD)
        return;
    else
        evt.eventStatus = EVENT_READED;
    
    self.selectEvent = evt;
    CameraPlaybackController *controller = [[CameraPlaybackController alloc] initWithNibName:@"CameraPlayback" bundle:nil];
    controller.camera = self.camera;
    controller.event = [event_list objectAtIndex:[indexPath row]];
    [self.navigationController pushViewController:controller animated:YES];
//    PlayBackViewController *vc = [PlayBackViewController new];
//    vc.camera = self.camera;
//    vc.event = [event_list objectAtIndex:[indexPath row]];
//    [self.navigationController pushViewController:vc animated:YES];

}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (event_list.count>0) {
        
    }else{
        
        return nil;
    }
   EventHeadView *headView = [EventHeadView headerViewWithTableView:tableView];

    headView.time.text = self.totalTime;
  
 
  /*  DeviceHeadView *headView = [DeviceHeadView headerViewWithTableView:tableView];
    headView.DeviceName.text = self.totalTime;
*/
    
    return headView;
    
}

#pragma mark - MyCameraDelegate Methods
- (void)camera:(MyCamera *)camera _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size{
    
    if (type == IOTYPE_USER_IPCAM_LISTEVENT_RESP) {
        SMsgAVIoctrlListEventResp *s = (SMsgAVIoctrlListEventResp *)data ;
        
        NSLog(@"s->total:%d, s->index:%d, s->endflag:%d, s->count:%d", s->total, s->index, s->endflag, s->count);
        
        if (s->total == 0) {
            return [SVProgressHUD showInfoWithStatus:@"没有数据"];
        }
        
        if (s->count > 0) {
            

            
            for (int i = 0; i < s->count; i++) {
                
                SAvEvent saEvt = s->stEvent[i];
                
                double timeInMillis = [self getTimeInMillis:saEvt.stTime];
                
                NSLog(@"<<< event:%d Get Event(%d): %d/%d/%d %d:%2d:%2d (%f)", saEvt.event, saEvt.status, saEvt.stTime.year, saEvt.stTime.month, saEvt.stTime.day, (int)saEvt.stTime.hour, (int)saEvt.stTime.minute, (int)saEvt.stTime.second, timeInMillis);
                
                Event *evt = [[Event alloc] initWithEventType:saEvt.event EventTime:[self getTimeInMillis:saEvt.stTime] EventStatus:saEvt.status];
                
                [event_list addObject:evt];
                
            }
            
            
            
        }
        
        
        if (1 == s->endflag) {
            
#if defined(SORTE_LIST)
            //降序
            NSComparator cmptr = ^(id obj1, id obj2){
                Event *evt1 = (Event *)obj1;
                Event *evt2 = (Event *)obj2;
                if (evt1.eventTime < evt2.eventTime) {
                    return (NSComparisonResult)NSOrderedDescending;
                }
                
                if (evt1.eventTime > evt2.eventTime) {
                    return (NSComparisonResult)NSOrderedAscending;
                }
                return (NSComparisonResult)NSOrderedSame;
            };
            
            
            //第一种排序
            NSArray *array = [event_list sortedArrayUsingComparator:cmptr];
            
            [event_list removeAllObjects];
            for(Event *evt0 in array){
                //NSLog(@"new evt0.eventTime:%ld", evt0.eventTime);
                
                [event_list addObject:evt0];
                
            }
            
            
#endif
            [SVProgressHUD dismiss];

            [self.tableView reloadData];
        }
        
        
    } else if (type == IOTYPE_USER_IPCAM_EDIT_FILES_RESP) {
        SMsgAVIoctrlEditfileResp *s = (SMsgAVIoctrlEditfileResp *)data;
        
        NSLog(@"IOTYPE_USER_IPCAM_EDIT_FILES_RESP s->command:%d",  s->command);
        
        if (FILE_EDIT_DOWN == s->command) {
            SMsgAVIoctrlEditfileResp2 *s2 = (SMsgAVIoctrlEditfileResp2 *)data;
            
            NSLog(@"s2->result:%d, s2->file_name:%s", s2->result, s2->file_name);
            NSLog(@"s2->result:%d, s2->file_path:%s", s2->result, s2->file_path);
            
            if (s2->result == 0) {
                
                
                self.selectFileName = [NSString stringWithFormat:@"%s", s2->file_name];
                self.selectFilePath = [NSString stringWithFormat:@"%s/%s", s2->file_path, s2->file_name];
                
                NSLog(@"self.selectFileName:%@", self.selectFileName);
                NSLog(@"self.selectFilePath:%@", self.selectFilePath);
                
            } else {
                self.selectFileName = [NSString stringWithFormat:@"%s", ""];
                self.selectFilePath = [NSString stringWithFormat:@"%s", ""];
                
            }
            
            
        } else if (FILE_EDIT_REMOVE == s->command) {
            
            NSLog(@"s->result:%d", s->result);
            
            if (0 == s->result) {
                
          /*      [self deleteSelectEvent:self.selectEvent];
                
                if (selectDeleteIndexPath) {
                    
                    NSLog(@"section:%ld  row:%ld", (long)[selectDeleteIndexPath section], (long)[selectDeleteIndexPath row]);
                    
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:selectDeleteIndexPath] withRowAnimation:UITableViewRowAnimationFade];
                    
                    selectDeleteIndexPath = nil;
                    
                    NSLog(@"deleteRowsAtIndexPaths ok");
                    
                }
                */
                
            } else {
//                [[iToast makeText:NSLocalizedString(@"Remote record delete failed", @"")]show];
                
            }
            
        }
        
        
    } else if (type == IOTYPE_USER_IPCAM_DOWNLOAD_FILE_RESP) {
        SMsgAVIoctrlDownloadFileResp *s = (SMsgAVIoctrlDownloadFileResp *)data;
        
        NSLog(@"s->result:%d", s->result);
        
        if (0 == s->result) {
//            isRecvDownloadFileResp = YES;
            
        }
        
    }

}



- (UITableView *)tableView{
    
    if (!_tableView) {
        
        __weak UIView *superView = self.view;
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [superView addSubview:_tableView];
        //        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;//隐藏tableView的分割线
        //        _tableView.scrollEnabled = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    
    return _tableView;
    
}

- (void)masLayoutSubview{
    
    __weak UIView *superView = self.view;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.mas_equalTo(superView);
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
